package com.wanmait.hotelManage.servlet;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.wanmait.hotelManage.dao.RoomTypeDAO;

import com.wanmait.hotelManage.dao.RoomimagesDAO;
import com.wanmait.hotelManage.vo.Pager;
import com.wanmait.hotelManage.vo.RoomType;
import com.wanmait.hotelManage.vo.Roomimages;

@WebServlet("/manage/RoomTypeServlet")
@MultipartConfig()
public class RoomTypeServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String action = request.getParameter("action");
		if("list".equals(action)) {
			this.list(request, response);
		}else if("delete".equals(action)) {
			this.delete(request, response);
		}else if("batchDelete".equals(action)) {
			this.batchDelete(request, response);
		}else if("updateInit".equals(action)) {
			this.updateInit(request, response);
		}else if("update".equals(action)) {
			this.update(request, response);
		}else if("beforeinsert".equals(action)) {
			this.beforeinsert(request, response);
		}else if("insert".equals(action)) {
			this.insert(request, response);
		}else if("getRoomTypes".equals(action)) {
			this.getRoomTypes(request, response);
		}
		
		
	}
	//分页显示房型
	protected void getRoomTypes(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pageNo = request.getParameter("pageNo");
		Pager pager=new Pager();
		pager.setPageSize(6);
		pager.setPageNo(Integer.parseInt(pageNo));
		int rows=RoomTypeDAO.getRoomtypedao().getRows();
		pager.setPageCount(rows);
		
		List<RoomType> roomTypes = RoomTypeDAO.getRoomtypedao().findAll(pager);
		request.setAttribute("roomTypes", roomTypes);
		request.setAttribute("pager", pager);
		request.getRequestDispatcher("/manage/roomType/showRoomTypeList.jsp").forward(request, response);
	}
	//获得文件名并写到服务器里
	public String getfilenameAndWrite(Part part,HttpServletRequest request) throws IOException {
		String header = part.getHeader("content-disposition");
		String fileext = header.substring(header.lastIndexOf("."), header.length()-1);
		String realPath=request.getServletContext().getRealPath("/static/images");
		String filename = UUID.randomUUID().toString();
		part.write(realPath+"/"+filename+fileext);
		part.delete();
		return filename+fileext;
	}
	//获得文件名并写到服务器里
	public String getfilenameAndWriteSlideshow(Part part,HttpServletRequest request) throws IOException {
		String header = part.getHeader("content-disposition");
		String fileext = header.substring(header.lastIndexOf("."), header.length()-1);
		String realPath=request.getServletContext().getRealPath("/static/images/rooms");
		String filename = UUID.randomUUID().toString();
		part.write(realPath+"/"+filename+fileext);
		part.delete();
		return filename+fileext;
	}
	//添加房型
	protected void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String title = request.getParameter("title");
		String price = request.getParameter("price");
		String discountPrice = request.getParameter("discountPrice");
		String description = request.getParameter("description");
		Part pic = request.getPart("pic");
		String picfilename = this.getfilenameAndWrite(pic, request);
		RoomType roomType=new RoomType();
		roomType.setDescription(description);
		roomType.setPrice(Double.parseDouble(price));
		roomType.setDiscountPrice(Double.parseDouble(discountPrice));
		roomType.setPic(picfilename);
		roomType.setTitle(title);
		RoomTypeDAO.getRoomtypedao().insert(roomType);
		Integer roomTypeId=RoomTypeDAO.getRoomtypedao().findRoomTypeId();
		Collection<Part> parts = request.getParts();
		for(Part part:parts) {
			if(part.getName().startsWith("images")) {
				String filename = this.getfilenameAndWriteSlideshow(part, request);
				RoomimagesDAO.getRoomimagesdao().insertImagesByRoomTypeId(filename,roomTypeId);
			}
		}
		response.sendRedirect(request.getContextPath()+"/manage/RoomTypeServlet?action=list");
	}
	//插入客房的客房类型初始化

	protected void beforeinsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<RoomType>roomtypes=RoomTypeDAO.getRoomtypedao().findAll();
		request.setAttribute("roomtypes", roomtypes);
		request.getRequestDispatcher("/manage/room/insert.jsp").forward(request, response);
	}
	//更新房型
	public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		RoomType roomType=new RoomType();
		roomType.setDescription(request.getParameter("description"));
		roomType.setDiscountPrice(Double.parseDouble(request.getParameter("discountPrice")));
		roomType.setId(Integer.parseInt(request.getParameter("id")));
		roomType.setPrice(Double.parseDouble(request.getParameter("price")));
		roomType.setTitle(request.getParameter("title"));
		roomType.setHot(request.getParameter("hot").equals("热门")?true:false);
		
		Part fengpart = request.getPart("picture");
		String header = fengpart.getHeader("content-disposition");

		int lastIndex= header.lastIndexOf(".");
		String fileext="";
		try {
			fileext = header.substring(lastIndex, header.length()-1);
		} catch (Exception e) {
			
		}
		if(fileext!="") {	
			String path=request.getServletContext().getRealPath("/static/images");
			String fileName = UUID.randomUUID().toString();
			fengpart.write(path+"/"+fileName+fileext);
			fengpart.delete();
			roomType.setPic(fileName+fileext);
			RoomTypeDAO.getRoomtypedao().update(roomType);
		}else {
			RoomTypeDAO.getRoomtypedao().noImageUpdate(roomType);
		}
		for(Part part:request.getParts()) {
			String partName=part.getName();
			if(partName.startsWith("pic")) {
				String id = partName.substring(3);
				String picheader = part.getHeader("content-disposition");
				int piclastIndex= picheader.lastIndexOf(".");
				String picfileext="";
				try {
					picfileext = picheader.substring(piclastIndex, picheader.length()-1);
				} catch (Exception e) {
					
				}
				if(picfileext!="") {	
					String path=request.getServletContext().getRealPath("/static/images/rooms");
					System.out.println(path);
					String fileName = UUID.randomUUID().toString();
					part.write(path+"/"+fileName+picfileext);
					part.delete();
//					roomType.setPic(fileName+picfileext);
					RoomimagesDAO.getRoomimagesdao().updatePicById(fileName+picfileext,Integer.parseInt(id));
				}else {
					//RoomTypeDAO.getRoomtypedao().noImageUpdate(roomType);
				}
	
			}
		}
		response.sendRedirect(request.getContextPath()+"/manage/RoomTypeServlet?action=list");
	}
	//更新页面初始化
	public void updateInit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer id = Integer.parseInt(request.getParameter("id"));
		RoomType roomType=RoomTypeDAO.getRoomtypedao().findRoomTypeById(id);
		List<Roomimages> roomTypeImages=RoomimagesDAO.getRoomimagesdao().findImagesByRoomTypeId(roomType);
		List<RoomType> roomTypes = RoomTypeDAO.getRoomtypedao().findAll();
		request.setAttribute("roomTypes", roomTypes);
		request.setAttribute("roomType", roomType);
		request.setAttribute("roomTypeImages", roomTypeImages);
		request.getRequestDispatcher("/manage/roomType/update.jsp").forward(request, response);
	}
	//批量删除
	public void batchDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String ids = request.getParameter("ids");
		RoomTypeDAO.getRoomtypedao().delete(ids);
	}
	//删除
	public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		RoomTypeDAO.getRoomtypedao().delete(Integer.parseInt(id));
	}
	//查询全部的roomType
	public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Pager pager=new Pager();
		pager.setPageSize(6);
		pager.setPageNo(1);
		int rows=RoomTypeDAO.getRoomtypedao().getRows();
		pager.setPageCount(rows);
		request.setAttribute("pager", pager);
		
		List<RoomType> roomTypes=RoomTypeDAO.getRoomtypedao().findAll(pager);
		request.setAttribute("roomTypes", roomTypes);
		request.getRequestDispatcher("/manage/roomType/list.jsp").forward(request, response);
	}

}
